import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:moonmate/utils/error_handler.dart';
import 'package:moonmate/utils/errors.dart';

/// 交互类型枚举
enum InteractionType {
  tap,      // 点击
  longPress, // 长按
  swipe,    // 滑动
  success,  // 成功
  error,    // 错误
  warning,  // 警告
  info,     // 信息
  loading,  // 加载中
  confirm,  // 确认
  cancel,   // 取消
}

/// 交互反馈服务
class InteractionService {
  // 单例模式
  static final InteractionService _instance = InteractionService._internal();
  factory InteractionService() => _instance;
  
  // 私有构造函数
  InteractionService._internal();
  
  // 加载指示器的上下文栈，用于嵌套加载时管理
  final List<BuildContext?> _loadingContexts = [];
  
  // 最后一次Toast显示时间，用于防止Toast过于频繁
  DateTime? _lastToastTime;
  // 防止连续点击的时间戳
  final Map<String, DateTime> _lastTapTimes = {};
  
  // 触觉反馈强度
  static const Map<InteractionType, HapticFeedbackType> _hapticTypes = {
    InteractionType.tap: HapticFeedbackType.lightImpact,
    InteractionType.longPress: HapticFeedbackType.mediumImpact,
    InteractionType.success: HapticFeedbackType.lightImpact,
    InteractionType.error: HapticFeedbackType.mediumImpact,
    InteractionType.warning: HapticFeedbackType.lightImpact,
    InteractionType.info: HapticFeedbackType.selectionClick,
    InteractionType.confirm: HapticFeedbackType.mediumImpact,
    InteractionType.cancel: HapticFeedbackType.lightImpact,
  };
  
  // 触觉反馈
  Future<void> provideHapticFeedback(InteractionType type) async {
    try {
      final hapticType = _hapticTypes[type];
      if (hapticType != null) {
        switch (hapticType) {
          case HapticFeedbackType.lightImpact:
            await HapticFeedback.lightImpact();
            break;
          case HapticFeedbackType.mediumImpact:
            await HapticFeedback.mediumImpact();
            break;
          case HapticFeedbackType.heavyImpact:
            await HapticFeedback.heavyImpact();
            break;
          case HapticFeedbackType.selectionClick:
            await HapticFeedback.selectionClick();
            break;
        }
      }
    } catch (e) {
      // 触觉反馈失败不影响应用
    }
  }
  
  // 防止重复点击的包装函数
  void debounceTap(String key, VoidCallback onTap, {int minDelayMs = 300}) {
    final now = DateTime.now();
    final lastTap = _lastTapTimes[key];
    
    if (lastTap == null || now.difference(lastTap).inMilliseconds >= minDelayMs) {
      _lastTapTimes[key] = now;
      onTap();
      provideHapticFeedback(InteractionType.tap);
    }
  }
  
  // 显示Toast提示
  void showToast(BuildContext context, String message, {
    InteractionType type = InteractionType.info,
    Duration duration = const Duration(seconds: 2),
    bool showHaptic = true,
  }) {
    // 防止Toast过于频繁
    final now = DateTime.now();
    if (_lastToastTime != null && 
        now.difference(_lastToastTime!).inMilliseconds < 500) {
      return;
    }
    
    _lastToastTime = now;
    
    // 触觉反馈
    if (showHaptic) {
      provideHapticFeedback(type);
    }
    
    // 颜色配置
    Color backgroundColor;
    switch (type) {
      case InteractionType.success:
        backgroundColor = Colors.green[600]!;
        break;
      case InteractionType.error:
        backgroundColor = Colors.red[600]!;
        break;
      case InteractionType.warning:
        backgroundColor = Colors.amber[600]!;
        break;
      case InteractionType.info:
      default:
        backgroundColor = Colors.grey[700]!;
        break;
    }
    
    // 显示SnackBar作为Toast
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          message,
          style: const TextStyle(color: Colors.white),
          textAlign: TextAlign.center,
        ),
        backgroundColor: backgroundColor,
        duration: duration,
        behavior: SnackBarBehavior.floating,
        margin: const EdgeInsets.all(16),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8),
        ),
      ),
    );
  }
  
  // 显示成功提示
  void showSuccessToast(BuildContext context, String message) {
    showToast(context, message, type: InteractionType.success);
  }
  
  // 显示错误提示
  void showErrorToast(BuildContext context, String message) {
    showToast(context, message, type: InteractionType.error);
  }
  
  // 显示警告提示
  void showWarningToast(BuildContext context, String message) {
    showToast(context, message, type: InteractionType.warning);
  }
  
  // 显示信息提示
  void showInfoToast(BuildContext context, String message) {
    showToast(context, message, type: InteractionType.info);
  }
  
  // 显示加载指示器
  void showLoading(BuildContext context, {String message = '加载中...'}) {
    // 防止重复显示
    if (_loadingContexts.isNotEmpty && _loadingContexts.last == context) {
      return;
    }
    
    _loadingContexts.add(context);
    
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          backgroundColor: Colors.transparent,
          elevation: 0,
          content: Center(
            child: Container(
              padding: const EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const CircularProgressIndicator(),
                  const SizedBox(height: 16),
                  Text(
                    message,
                    style: const TextStyle(fontSize: 16),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
  
  // 隐藏加载指示器
  void hideLoading(BuildContext context) {
    if (_loadingContexts.isNotEmpty) {
      _loadingContexts.remove(context);
      Navigator.of(context).pop();
    }
  }
  
  // 显示确认对话框
  Future<bool> showConfirmDialog(
    BuildContext context,
    String title,
    String message,
    {
      String confirmText = '确定',
      String cancelText = '取消',
      InteractionType type = InteractionType.confirm,
    }
  ) async {
    provideHapticFeedback(type);
    
    final result = await showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(title),
          content: Text(message),
          actions: <Widget>[
            TextButton(
              child: Text(cancelText),
              onPressed: () {
                provideHapticFeedback(InteractionType.cancel);
                Navigator.of(context).pop(false);
              },
            ),
            TextButton(
              child: Text(
                confirmText,
                style: TextStyle(
                  color: type == InteractionType.error ? Colors.red : null,
                ),
              ),
              onPressed: () {
                provideHapticFeedback(InteractionType.confirm);
                Navigator.of(context).pop(true);
              },
            ),
          ],
        );
      },
    );
    
    return result ?? false;
  }
  
  // 显示带输入的对话框
  Future<String?> showInputDialog(
    BuildContext context,
    String title,
    String hintText,
    {
      String initialValue = '',
      bool obscureText = false,
      TextInputType keyboardType = TextInputType.text,
      List<TextInputFormatter>? inputFormatters,
      String confirmText = '确定',
      String cancelText = '取消',
      bool Function(String)? validator,
    }
  ) async {
    final TextEditingController controller = 
        TextEditingController(text: initialValue);
    
    final result = await showDialog<String>(
      context: context,
      builder: (BuildContext context) {
        String? errorMessage;
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: Text(title),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextField(
                    controller: controller,
                    decoration: InputDecoration(
                      hintText: hintText,
                      errorText: errorMessage,
                    ),
                    obscureText: obscureText,
                    keyboardType: keyboardType,
                    inputFormatters: inputFormatters,
                    autofocus: true,
                  ),
                ],
              ),
              actions: <Widget>[
                TextButton(
                  child: Text(cancelText),
                  onPressed: () {
                    provideHapticFeedback(InteractionType.cancel);
                    Navigator.of(context).pop(null);
                  },
                ),
                TextButton(
                  child: Text(confirmText),
                  onPressed: () {
                    final input = controller.text.trim();
                    
                    if (validator != null) {
                      if (!validator(input)) {
                        // 验证失败
                        setState(() {
                          errorMessage = '输入无效';
                        });
                        return;
                      }
                    }
                    
                    provideHapticFeedback(InteractionType.confirm);
                    Navigator.of(context).pop(input);
                  },
                ),
              ],
            );
          },
        );
      },
    );
    
    controller.dispose();
    return result;
  }
  
  // 显示底部操作菜单
  Future<String?> showBottomSheetAction(
    BuildContext context,
    String title,
    List<String> actions,
    {List<IconData>? icons,
    bool allowCancel = true}
  ) async {
    provideHapticFeedback(InteractionType.swipe);
    
    return showModalBottomSheet<String>(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(16),
                child: Text(
                  title,
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              for (int i = 0; i < actions.length; i++)
                ListTile(
                  leading: icons != null && i < icons.length
                      ? Icon(icons[i])
                      : null,
                  title: Text(actions[i]),
                  onTap: () {
                    provideHapticFeedback(InteractionType.tap);
                    Navigator.of(context).pop(actions[i]);
                  },
                ),
              if (allowCancel)
                Divider(),
              if (allowCancel)
                ListTile(
                  title: const Text(
                    '取消',
                    textAlign: TextAlign.center,
                    style: TextStyle(color: Colors.grey),
                  ),
                  onTap: () {
                    provideHapticFeedback(InteractionType.cancel);
                    Navigator.of(context).pop(null);
                  },
                ),
            ],
          ),
        );
      },
    );
  }
  
  // 处理异步操作，提供加载状态和错误处理
  Future<T?> handleAsyncOperation<T>(
    BuildContext context,
    Future<T> Function() operation,
    {
      String loadingMessage = '处理中...',
      String successMessage = '操作成功',
      bool showSuccessMessage = true,
      bool showLoading = true,
      bool showError = true,
      void Function(AppError)? onError,
      ErrorHandler? errorHandler,
    }
  ) async {
    try {
      if (showLoading) {
        this.showLoading(context, message: loadingMessage);
      }
      
      final result = await operation();
      
      if (showSuccessMessage && successMessage.isNotEmpty) {
        showSuccessToast(context, successMessage);
      }
      
      return result;
    } catch (e) {
      final appError = (errorHandler ?? ErrorHandler())
          .handleError(e, 'AsyncOperation');
      
      if (showError) {
        if (onError != null) {
          onError(appError);
        } else {
          showErrorToast(context, appError.message);
        }
      }
      
      return null;
    } finally {
      if (showLoading) {
        hideLoading(context);
      }
    }
  }
  
  // 清理资源
  void dispose() {
    _loadingContexts.clear();
    _lastTapTimes.clear();
  }
}

// 触觉反馈类型枚举
enum HapticFeedbackType {
  lightImpact,    // 轻微触感
  mediumImpact,   // 中等触感
  heavyImpact,    // 强烈触感
  selectionClick, // 选择点击
}